<?php
namespace app\admin\controller;

use app\common\business\Images;
use app\common\lib\Param;
use app\common\lib\Show;
use think\response\Json;

class File extends AdminBase
{
    public function list(){
        list($page,$limit,$fileType) = Param::getMore([
            ['page', null],
            ['limit', null],
            ['fileType', null],
        ], $this->request, true);

        $where = [];
        $fileBis = new \app\common\business\File();
        if(in_array($fileType,[1,2])){
            $fileType == 1 && $where[] = ['att_type','in',$fileBis->allowImageExt];
            $fileType == 2 && $where[] = ['att_type','in',$fileBis->allowVideoExt];
        }
        try {
            $result=(new \app\common\business\Images())->getTableList($page,$limit,$where);
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        return Show::success($result);
    }

    public function uploadFile(): Json
    {
        $file=$this->request->file('file');
        try {
            $url=(new \app\common\business\File())->uploadFile($file);
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }

        //存入images表
        $data = [
            'att_dir'=>$url,
            'att_type'=>pathinfo($url,PATHINFO_EXTENSION),
        ];
        try {
            $result = (new Images())->save($data);
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }

        return Show::success($result);
    }

    public function deleteFile(): Json
    {
        $ids=$this->request->post('ids');
        try {
            $result=(new \app\common\business\Images())->deleteByIds($ids);
        }catch (\Exception $e){
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success([], "删除成功");
        }
        return Show::error([], '删除失败');
    }
}
